package jp.ac.waseda.info.ueda.unyo.customReallocator;

import java.io.File;

import jp.ac.waseda.info.ueda.unyo.container.CustomReallocatorContainer;
import jp.ac.waseda.info.ueda.unyo.manager.ConfManager;
import jp.ac.waseda.info.ueda.unyo.util.Logger;

public class PluginLoader {
	
	final static
	private String CLASS = ".class";

	static
	public void load(){

		String userDir = System.getProperty("user.dir");
		File pluginDir = new File(userDir + File.separator + PluginCompiler.PLUGIN_DIRECTORY);
		File pluginDir2 = new File(userDir + File.separator + PluginCompiler.AUTO_PLUGIN_DIRECTORY);
		String[] files = pluginDir.list();
		String[] files2 = pluginDir2.list();
		if(files == null && files2 == null){
			return;
		}
		if(files != null){
			for (String file : files) {
				if(!file.endsWith(CLASS)){
					continue;
				}
				try {
					Logger.sysinfo(Logger.MSG_LOADING_PLUGIN + file);
					String fileName = file.substring(0, file.length() - CLASS.length());
					Class<?> pluginClass = Class.forName(PluginCompiler.PLUGIN_DIRECTORY + "." + fileName);
					Object pluginObj = pluginClass.newInstance();
					CustomReallocatorContainer.addCustomReallocator(pluginObj);
					Logger.sysinfo(Logger.MSG_DONE);
					
				} catch (SecurityException e) {
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					e.printStackTrace();
				} catch (InstantiationException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				}
			}
		}
		if(files2 != null){
			for (String file : files2) {
				if(!file.endsWith(CLASS)){
					continue;
				}
				try {
					Logger.sysinfo(Logger.MSG_LOADING_PLUGIN + file);
					String fileName = file.substring(0, file.length() - CLASS.length());
					Class<?> pluginClass = Class.forName(PluginCompiler.PLUGIN_DIRECTORY + "." + PluginCompiler.PLUGIN_AUTO + "." + fileName);
					Object pluginObj = pluginClass.newInstance();
					CustomReallocatorContainer.addAutoCustomReallocator(pluginObj, fileName);
					Logger.sysinfo(Logger.MSG_DONE);
					
				} catch (SecurityException e) {
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					e.printStackTrace();
				} catch (InstantiationException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				}
			}
		}
		ConfManager.load();
	}
}
